<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, reactive, onMounted, h } from 'vue'
import { CustomSearch } from '@/components/CustomSearch'
import { Table, TableColumn } from '@/components/Table'
import { FormSchema } from '@/components/Form'
import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ElMessage, ElUpload, ElButton, ElDialog } from 'element-plus'
import { allWorkOrdersData } from '@/views/qualityWorkOrder/wkOrderData'
// 引入质检记录弹窗组件
import QualityRecordDialog from './components/QualityRecordDialog.vue'
import { inject } from 'vue'
const { t } = useI18n()

// 搜索相关
const { searchRegister, searchMethods } = useSearch()
const searchRef = ref(null)
const { setSchema, getFormData } = searchMethods

// 多选相关数据
const selectedRows = ref<any[]>([])

// 加载状态
const isQualityChecking = ref(false)

// 处理多选变化
const handleSelectionChange = (selection: any[]) => {
  console.log('selection', selection)
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

// 搜索表单配置
const schema = reactive<FormSchema[]>([
  {
    field: 'mgtOrgName',
    label: '管理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入管理单位'
    }
  },
  {
    field: 'custNo',
    label: '用户编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户编号'
    }
  },
  {
    field: 'wkOrderNo',
    label: '工单编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入工单编号'
    }
  },
  {
    field: 'wkOrderStatName',
    label: '工单状态',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择工单状态',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: false,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: [
        { label: '全部', value: '全部' },
        { label: '挂起', value: '挂起' },
        { label: '作废', value: '作废' },
        { label: '归档', value: '归档' },
        { label: '在途', value: '在途' }
      ],
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'field1',
    label: '用电类别',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用电类别'
    }
  },
  {
    field: 'wkOrderType',
    label: '工单类型',
    component: 'Input',
    componentProps: {
      placeholder: '请输入工单类型'
    }
  }
])

// 使用useTable hook进行表格数据管理
const { tableRegister, tableMethods, tableState } = useTable({
  immediate: true, // 立即请求
  fetchDataApi: async () => {
    try {
      // 获取搜索表单数据
      const formData = await getFormData()
      console.log('整改页面formData:', formData)

      // 模拟API请求 - 实际项目中应替换为真实API
      // 这里使用setTimeout模拟网络请求
      return new Promise((resolve) => {
        setTimeout(() => {
          // 这里是模拟数据，实际应该从后端API获取

          const mockData = allWorkOrdersData;

          // 根据查询条件过滤数据
          const filteredData = mockData.filter((item) => {
            if (formData.mgtOrgName && !item.mgtOrgName.includes(formData.mgtOrgName)) return false
            if (formData.custNo && !item.custNo.includes(formData.custNo)) return false
            if (formData.wkOrderNo && !item.wkOrderNo.includes(formData.wkOrderNo)) return false
            if (formData.wkOrderStatName && item.wkOrderStatName !== formData.wkOrderStatName) return false
            if (formData.wkOrderType && !item.wkOrderType.includes(formData.wkOrderType)) return false
            return true
          })

          // 返回查询结果
          resolve({
            list: filteredData,
            total: filteredData.length
          })
        }, 500)
      })
    } catch (error) {
      return Promise.reject(error)
    }
  }
})

// 从useTable中解构获取数据和状态
const { dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

// 表格列配置
const columns = reactive<TableColumn[]>([
  {
    field: '',
    type: 'selection',
    width: 60,
    selection: true
  },
  {
    field: 'mgtOrgName',
    label: '管理单位',
    minWidth: 150
  },
  {
    field: 'prntMgtOrgName',
    label: '供电所',
    minWidth: 150
  },
  {
    field: 'wkOrderNo',
    label: '工单编号',
    minWidth: 150
  },
  {
    field: 'wkOrderType',
    label: '工单类型',
    minWidth: 150
  },
  {
    field: 'wkOrderClass',
    label: '工单分类',
    minWidth: 150
  },
  {
    field: 'procName',
    label: '流程名称',
    minWidth: 150
  },
  {
    field: 'custNo',
    label: '用户编号',
    minWidth: 150
  },
  {
    field: 'wkOrderStatName',
    label: '处理状态',
    minWidth: 150
  }
])

// 处理重置
const handleReset = async () => {
  // 将重置页面和刷新数据交给Search组件完成
  currentPage.value = 1
  refresh()
}

// 处理查询
const handleSearch = async () => {
  currentPage.value = 1
  refresh()
}

const { setProps } = tableMethods
// 在组件挂载后注册Search组件
onMounted(() => {
  // 设置固定表格高度 437.8
  setProps({
    height: 438
  })
  // 注册搜索组件
  if (searchRef.value) {
    searchRegister(searchRef.value)

    // 统一设置所有表单项的大小和宽度
    schema.forEach((item) => {
      setSchema([
        {
          field: item.field,
          path: 'componentProps.size',
          value: 'default'
        },
        {
          field: item.field,
          path: 'componentProps.style',
          value: { width: '300px' }
        }
      ])
    })
  }
})

/**
 * 从对象数组中提取指定字段的值，生成去重集合，再转换为字符串
 * @param array 源对象数组
 * @param field 要提取的字段名
 * @param separator 字符串分隔符，默认为逗号
 * @returns 提取后的值组成的字符串
 */
function extractFieldToString<T extends Record<string, any>>(
  array: T[],
  field: keyof T,
  separator: string = ','
): string {
  if (!Array.isArray(array)) {
    throw new Error('第一个参数必须是数组');
  }

  // 提取字段值并去重（使用Set）
  const uniqueValues = new Set<T[keyof T]>(
    array.map(item => item[field]).filter(value => value !== undefined && value !== null)
  );

  // 转换为数组并拼接成字符串
  return Array.from(uniqueValues).join(separator);
}


// 表格样式，奇行背景色#f6f6f6偶行背景色#ffffff
const tableRowStyle = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? { background: '#ffffff' } : { background: '#fcfcfc' }
}


// 添加百炼平台API相关配置
const WORKFLOW_ID = '7f3739da1269467f8aa80c5093e5a6b1'
const BAILIAN_API_URL = `https://dashscope.aliyuncs.com/api/v1/apps/${WORKFLOW_ID}/completion` // 假设的百炼平台API地址

// 添加质检记录相关状态
const qualityRecords = ref<any[]>([])

// 注入父组件提供的方法
const updateQualityWorkOrders = inject('updateQualityWorkOrders') as (orders: any[]) => void
// 质检工单数据
const qualityWorkOrders = ref<any[]>([])

// 添加调用百炼工作流的方法
const callBailianWorkflow = async () => {
  try {
    const wkOrdersString = extractFieldToString(selectedRows.value, 'dialogueCont', ';');
    // 构建请求体
    const payload = {
      // 传递选中的工单信息
      input: {
        prompt: "你是一名电网业扩工单质检规则研判专家，需对工单信息精准识别敏感词（含关键词及相近词），并严格依据以下细化标准判断触发的敏感词类别，输出结构化结果。",
        biz_params: {
          orders: wkOrdersString
        }
      },
      // orders: wkOrdersString,
      parameters: {},
      debug: {},
    }

    // 发送请求到百炼平台
    const response = await fetch(BAILIAN_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sk-ce1ee9ac29134f548aa97ac4fcffb729' // 需要替换为实际的认证令牌
      },
      body: JSON.stringify(payload)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    // 处理百炼平台返回结果，生成质检记录
    const inspectionDate = new Date().toISOString().split('T')[0]

    // 获取当天已生成的质检报告次数
    const todayRecords = qualityRecords.value.filter(record =>
      record.inspectionDate === inspectionDate
    )
    const todayCount = todayRecords.length + 1

    const documentName = `质检报告-${inspectionDate.replace(/-/g, '')}-${todayCount}`

    // 解析质检工单信息
    const workOrders = parseQualityWorkOrders(result.output?.text || result.text || result)

    // 保存质检记录
    const newRecord = {
      id: Date.now(),
      inspectionDate: inspectionDate,
      documentName: documentName,
      operation: '下载',
      content: result.output?.text || result.text || result
    }

    qualityRecords.value.unshift(newRecord)

    // 保存质检工单数据
    if (workOrders.length > 0) {
      qualityWorkOrders.value = [...qualityWorkOrders.value, ...workOrders]
      // 正则表达式：匹配纯数字字符串
      const numericRegex = /^[0-9]+$/;
      // 过滤所有全数字字符串
      qualityWorkOrders.value = qualityWorkOrders.value.filter(item => {
        // 获取属性值并转为字符串（防止非字符串类型）
        const value = String(item['wkOrderNo']);
        // 测试是否全为数字
        return numericRegex.test(value);
      });
      // 保存到localStorage
      localStorage.setItem('qualityWorkOrders', JSON.stringify(qualityWorkOrders.value))

      // 通知父组件更新质检工单数据
      if (updateQualityWorkOrders) {
        updateQualityWorkOrders(qualityWorkOrders.value)
      }
    }

    // 保存到localStorage（实际项目中应该保存到后端）
    localStorage.setItem('qualityRecords', JSON.stringify(qualityRecords.value))

    // 处理成功响应
    ElMessage.success('质检任务已完成，质检记录已生成')
    console.log('百炼平台返回结果:', result)

    return result
  } catch (error) {
    console.error('调用百炼工作流失败:', error)
    ElMessage.error('质检任务提交失败，请检查网络连接或联系管理员')
    throw error
  }
}

// 解析质检工单信息
const parseQualityWorkOrders = (markdownContent: string) => {
  const workOrders: any[] = []

  try {
    // 提取"五、质检工单信息"部分的表格数据
    const workOrderMatch = markdownContent.match(/五、质检工单信息\s*\n(.*?)(?=\n\n---|$)/s)

    if (workOrderMatch) {
      const tableContent = workOrderMatch[1].trim()

      // 解析markdown表格
      const lines = tableContent.split('\n')
      let isInTable = false
      let headers: string[] = []

      lines.forEach((line, index) => {
        const trimmedLine = line.trim()

        // 跳过空行和分隔行
        if (!trimmedLine || trimmedLine.includes('---')) {
          return
        }

        // 检查是否是表格行
        if (trimmedLine.startsWith('|') && trimmedLine.endsWith('|')) {
          const cells = trimmedLine.split('|').map(cell => cell.trim()).filter(cell => cell)

          if (!isInTable) {
            // 第一行是表头
            headers = cells
            isInTable = true
          } else if (cells.length === headers.length) {
            // 数据行
            const workOrder: any = {}

            headers.forEach((header, cellIndex) => {
              const value = cells[cellIndex] || ''

              // 根据表头映射字段
              switch (header) {
                case '质检工单编号':
                  workOrder.wkOrderNo = value
                  break
                case '被质检工单编号（业扩工单编号）':
                case '被质检工单编号':
                  workOrder.qlwkOrderNo = value
                  break
                case '被质检工单类型':
                  workOrder.wkOrderType = value
                  break
                case '被质检工单分类':
                  workOrder.wkOrderClass = value
                  break
                case '供电单位':
                  workOrder.mgtOrgName = value
                  break
                case '供电所':
                  workOrder.prntMgtOrgName = value
                  break
                case '是否重要客户':
                  workOrder.isImportant = value
                  break
                case '质检创建时间':
                  workOrder.createTime = value
                  break
                case '质检原因':
                  workOrder.qualityReason = value
                  break
                default:
                  workOrder[header] = value
              }
            })

            // 添加默认值
            workOrder.id = Date.now() + index
            // workOrder.wkOrderNo = workOrder.wkOrderNo || `QG${Date.now()}${index}`
            // workOrder.mgtOrgName = workOrder.mgtOrgName || '国网湖北省电力公司'
            // workOrder.prntMgtOrgName = workOrder.prntMgtOrgName || '武汉供电所'
            workOrder.isImportant = workOrder.isImportant || '否'
            workOrder.custNo = '202501140905310'
            // workOrder.qualityReason = workOrder.qualityReason || '定期质检'
            // workOrder.createTime = workOrder.createTime || new Date().toISOString().replace('T', ' ').substring(0, 19)

            workOrders.push(workOrder)
          }
        }
      })
    }
  } catch (error) {
    console.error('解析质检工单信息失败:', error)
  }

  return workOrders
}

// 处理一键质检逻辑
const handleOneKeyQualityCheck = async () => {
  // 检查是否有选中的行数据
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据进行一键质检！')
    return
  }

  // 检查选中的数据状态，只允许质检特定状态的工单
  const validOrders = selectedRows.value.filter(order => {
    return order.wkOrderStatName === '在途'
  })

  if (validOrders.length !== 0) {
    ElMessage.warning('只能查看已归档状态的工单质检记录！')
    return
  }

  // 设置加载状态
  isQualityChecking.value = true

  try {
    await callBailianWorkflow()
  } finally {
    // 无论成功还是失败，都要解除加载状态
    isQualityChecking.value = false
  }
}

// 质检记录弹窗相关状态和方法
const qualityRecordDialogVisible = ref(false)

const openQualityRecordDialog = () => {
  // 从localStorage加载质检记录
  const savedRecords = localStorage.getItem('qualityRecords')
  if (savedRecords) {
    qualityRecords.value = JSON.parse(savedRecords)
  }
  // 打开质检记录弹窗
  qualityRecordDialogVisible.value = true
}

</script>

<template>
  <ContentWrap title="">
    <!-- 搜索表单 - 使用项目封装的Search组件 -->
    <CustomSearch ref="searchRef" :schema="schema" label-width="100px" :layout="'bottom'" :button-position="'right'"
      @search="handleSearch" @reset="handleReset" :custom-buttons="[
        {
          label: isQualityChecking ? '质检中...' : '一键质检',
          type: 'success',
          icon: isQualityChecking ? 'vi-ep:loading' : 'vi-ep:upload-filled',
          color: '#286af6',
          onClick: handleOneKeyQualityCheck,
          disabled: isQualityChecking
        },
        {
          label: '质检记录',
          type: 'success',
          plain: true,
          icon: 'vi-ep:chat-dot-square',
          color: '#286af6',
          onClick: openQualityRecordDialog
        }
      ]">

    </CustomSearch>

    <!-- 表格 - 使用项目封装的Table组件 -->
    <div style="margin-top:20px">
      <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :loading="tableState.loading.value"
        :data="dataList" :columns="columns" row-key="" height="450" :fit="true" :pagination="{
          total: total,
          pageSize: pageSize,
          currentPage: currentPage,
          pageSizes: [10, 20, 30, 40, 50],
          background: true
        }" style="
        --el-table-border-color: #cdd7d5;
        --el-table-text-color: #171717;
        --el-table-header-text-color: #585858;
      " :header-cell-style="() => ({
        'background-color': '#e5f5f3', // 背景色
        color: '#585858' // 文字颜色
      })" :row-style="tableRowStyle" @register="tableRegister" @selection-change="handleSelectionChange" />
    </div>
  </ContentWrap>
  <!-- 质检记录弹窗 -->
  <QualityRecordDialog v-model:visible="qualityRecordDialogVisible" :selected-orders="selectedRows"
    :quality-records="qualityRecords" @update-records="(records: any[]) => qualityRecords.value = records" />

</template>

<style lang="scss" scoped>
.operation-button {
  margin-left: 8px;
}

.mr-5px {
  margin-right: 5px;
}

/* 导入对话框样式 */
.import-dialog-content {
  padding: 20px 0;

  .upload-area {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;

    .upload-dragger {
      width: 100%;
    }

    .upload-icon {
      font-size: 48px;
      color: #409eff;
      margin-bottom: 10px;
    }

    .upload-text {
      text-align: center;
      color: #606266;

      .upload-hint {
        font-size: 12px;
        color: #909399;
        margin-top: 5px;
      }
    }
  }

  .template-download {
    text-align: center;
    margin-top: 20px;
  }
}

// /* 悬浮聊天按钮样式 */
// .floating-chat-button {
//   position: fixed;
//   right: 20px;
//   bottom: 160px;
//   z-index: 999;

//   .ai-chat-button {
//     display: flex;
//     flex-direction: column;
//     align-items: center;
//     background-color: #ffffff;
//     border-radius: 16px;
//     box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.12);
//     padding: 12px;
//     cursor: pointer;
//     width: 90px;
//     height: 120px;
//     transition: all 0.3s;

//     &:hover {
//       box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.15);
//       transform: translateY(-3px);
//     }

//     .robot-icon {
//       width: 60px;
//       height: 60px;
//       margin-bottom: 8px;

//       img {
//         width: 100%;
//         height: 100%;
//       }
//     }

//     .text-content {
//       display: flex;
//       flex-direction: column;
//       align-items: center;
//       color: #4e7ae7;

//       .sub-text {
//         font-size: 14px;
//         line-height: 1.2;
//       }
//     }
//   }
// }

// .chat-dialog {
//   :deep(.el-dialog__body) {
//     padding: 0;
//   }
// }</style>
